package com.yunlinker.asba.helper;

import android.app.Activity;

import java.util.ArrayList;
import java.util.Stack;

public class MyActivityManager  {
	private static Stack<Activity> activityStack;
	public static ArrayList<String> stackTagList = new ArrayList<>();
	private static MyActivityManager instance;

	private MyActivityManager() {
	}

	public static void clearTag(){
		stackTagList.clear();
	}

	public static int getASize(){
		return activityStack.size();
	}

	public static MyActivityManager getScreenManager() {
		if (instance == null) {
			instance = new MyActivityManager();
		}
		return instance;
	}

	// 退出栈顶Activity
	public void popActivity(Activity activity,String tag) {
		if (activity != null) {
			// 在从自定义集合中取出当前Activity时，也进行了Activity的关闭操作
			activity.finish();
			if(stackTagList.contains(tag)){
				stackTagList.remove(tag);
			}
			activityStack.remove(activity);
			activity = null;
		}
	}

	/**
	 * 弹出多个Activity
	 */
	public void popActivity(int num){
		/**
		 * 如果参数大于栈中activity数量，则num置为栈中activity数量
		 */
		num = (activityStack.size()<num?activityStack.size():num);
		for(;num>0;num--){
			/**
			 * 调用无参pop()弹出栈顶;
			 */
			popActivity();
		}
	}

	public void popActivity(){
		//如果已经到了栈底,显然需要退出程序
		boolean exitFlag=false;
		if(activityStack.size()==0){
            /*栈为空*/
			return;
		}else if(activityStack.size()==1) {
            /*到了栈底，应该退出App*/
			exitFlag=true;
		}
		//finish栈顶activity
		activityStack.get(activityStack.size()-1).finish();
		//在栈中移除栈顶
		activityStack.remove(activityStack.size()-1);
		//退出App
		if(exitFlag){
			System.exit(0);
		}
	}

	// 获得当前栈顶Activity
	public Activity currentActivity() {
		Activity activity = null;
		if(activityStack!=null){
			if (!activityStack.empty())
				activity = activityStack.lastElement();
		}
		return activity;
	}

	// 将当前Activity推入栈中
	public void pushActivity(Activity activity,String tag) {
		if (activityStack == null) {
			activityStack = new Stack<Activity>();
		}
		stackTagList.add(tag);

		activityStack.add(activity);
	}

	// 退出栈中所有Activity
	public void popAllActivityExceptOne(Class<?> cls) {
		stackTagList.clear();
		while (true) {
			Activity activity = currentActivity();
			if (activity == null) {
				break;
			}
			if (activity.getClass().equals(cls)) {
				popActivity(activity,"");
				continue;
			}
			popActivity(activity,"");
		}
	}
}
